
"use strict";

const arc_face = require('./modual/face_engine');
const path = require('path');
const config = require('./modual/config');
const m = require('.//modual/logger');
const client = require('.//modual/clients');
const imageHelper = require('./modual/face_cv_image');
const fsUtil = require('.//modual/fileUtils');
const cv = require('opencv4nodejs');
let fileCv = path.join(__dirname, './img/faces');

module.exports = {
    initFaceEngine,
    detectFaceFromFile,
    detectFaceFromBase64,
    extractFeature,
    featureProcess,
    releaseEngine,
};

// 初始化引擎
function initFaceEngine(){
    try{
        // 设置dll路径
        let dll = "";
        if (process.env.NODE_ENV !== 'development') {
            dll = process.cwd().replace(/\\/g, '\\\\') + '\\\\'
                + path.join(__dirname, '/../main/lib/X64').replace(/\\/g, '\\\\')
        }else{
            dll = process.cwd().replace(/\\/g, '\\\\') + '\\\\'
                + path.join(__dirname, '/lib/X64').replace(/\\/g, '\\\\')
        }

        // console.log("dll",dll)
        // 添加DLL所在目录到环境变量
        process.env['PATH'] = `${process.env.PATH};${dll}`;

        // 初始化
        const arc = new arc_face.default(config.lib_win64);

        let activeFileInfo = arc.getActiveFileInfo();
        if (null != activeFileInfo){
            let start = new Date(parseInt(activeFileInfo.startTime) * 1000);
            let end = new Date(parseInt(activeFileInfo.endTime) * 1000);

            m.logger.info("expire date is from %s to %s, please check the date for expired.thank you.",
                start.toLocaleString(),
                end.toLocaleString()
            );

            if (new Date().getTime() > end){
                m.logger.warn('your arc soft is expired,please change the file to continue use it,thank you.');
                return null;
            }
        }
        client.get('active', (err, res) => {
            // 激活
            if (!res || parseInt(res) !== 1){
                let ib = arc.activeFaceEngine(config.appId,config.appKey);
                client.set('active',ib?1:0);
            }else{
                m.logger.info("engine has already initialed, do not repeat active");
            }
        });

        let version = arc.getVersion();
        m.logger.info("current version is %s",version.Version);

        // 初始化引擎
        arc.initialFaceEngine(12,50);

        // 设置可信度
        arc.setLiveParam(0.5,0.7);

        return arc;
    }catch (e) {
        m.logger.error("face.js-initFaceEngine error:%o",e);
        return null;
    }

};

// 检测人脸并返回坐标
function detectFaceFromFile(arcx, imgFile) {
    try{
        let img = imageHelper.cvImages(imgFile,false,fileCv);
        return arcx.detectFacesEx(img.imageData);
    }catch (e) {
        m.logger.error("face.js-detectFaceFromFile error:%o",e);
        return null;
    }
}


// 检测人脸并返回坐标
function detectFaceFromBase64(arcx, img64) {
    try{
        let img = imageHelper.cvImagesBase64(img64,false,fileCv);
        if (!img){
            m.logger.warn("face.js-detectFaceFromBase64 error:img is null.");
            return null;
        }
        return arcx.detectFacesEx(img.imageData);
    }catch (e) {
        m.logger.error("face.js-detectFaceFromBase64 error:%o",e);
        return null;
    }
}

// 提取特征值
function extractFeature(arcx,imgData, rect, orient) {
    try{
        return arcx.extractFeature(imgData, rect, orient);
    }catch (e) {
        m.logger.error("face.js-extractFeature error:%o",e);
        return null;
    }
}

// 单体检测
function featureProcess(arcx,imgData,multiInfo,options,isIR,isDetect) {
    try{
        let ib = arcx.processEx(imgData,multiInfo,isIR,isDetect);
        if (!ib){
            m.logger.error("single process checked failed.");
            return;
        }
        let info = {
            sex: undefined,
            age: undefined,
            angle: undefined,
            live: undefined,
        };
        let sex,age,angle,live;
        switch (options) {
            case 1:
                sex = arcx.getSexInfo();
                break;
            case 2:
                sex = arcx.getSexInfo();
                age = arcx.getAgeInfo();
                break;
            case 3:
                sex = arcx.getSexInfo();
                age = arcx.getAgeInfo();
                angle =  arcx.getAngleInfo();
                break;
            case 4:
                sex = arcx.getSexInfo();
                age = arcx.getAgeInfo();
                angle =  arcx.getAngleInfo();
                live =  arcx.getLivenessScore(isIR);
                break;
        }

        info.sex = sex;
        info.age = age;
        info.angle = angle;
        info.live = live;

        return info;
    }catch (e) {
        m.logger.error("face.js-featureProcess error:%o",e);
    }
}


// 释放资源
function releaseEngine(arcx) {
    try{
        arcx.unInitialEngine();
    }catch (e) {
        m.logger.error("face.js-releaseEngine error:%o",e);
    }
}
